#include "mywidget.h"
#include "ui_mywidget.h"
#include <QDebug>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QCloseEvent>
#include <QMessageBox>

MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MyWidget)
{
    ui->setupUi(this);

    // 启动定时器, ms 为单位
    this->timerId = this->startTimer(1000);
    this->timerId2 = this->startTimer(500);


    connect(this->ui->pushButton, &MyButton::clicked,
            [=]() {
                qDebug() << "按钮被按下";
            });

}

MyWidget::~MyWidget()
{
    delete ui;
}

void MyWidget::keyPressEvent(QKeyEvent *ev) {
    qDebug() << (char) ev->key();
    if (ev->key() == Qt::Key_A) {
        qDebug() << "按键 A 被按下";
    }
}

void MyWidget::keyReleaseEvent(QKeyEvent *ev) {
    qDebug() << ev->key();
}

void MyWidget::timerEvent(QTimerEvent *ev) {

    int timer = ev->timerId();

    if (timer == this->timerId) {
        static int sec = 0;
        QString timerText = QString("<center><h1>time1 out %1</h1></center>").arg(sec++);
        ui->label->setText(timerText);

        // sec = 5 时关闭计时器
        if (sec == 5) {
            // 停止计数
            this->killTimer(this->timerId);
        }
    } else if (timer == this->timerId2) {
        static int sec = 0;
        QString timerText = QString("<center><h1>timer2 out %1</h1></center>").arg(sec++);
        ui->label_2->setText(timerText);
    }
}

// 窗口的鼠标按下事件
void MyWidget::mousePressEvent(QMouseEvent *ev) {
    qDebug() << "+++++++++++++++++++";
}

void MyWidget::closeEvent(QCloseEvent *ev) {

    int ret = QMessageBox::question(this, "question", "确认关闭");
    if (ret == QMessageBox::Yes) {
        // 关闭窗口
        // 处理关闭事件, 接收事件, 事件就不会往父组件传递


    } else {
        // 不关闭窗口
        // 忽略事件, 事件继续传递给父组件
        ev->ignore();
    }


}
